<template>
    <div id="container"></div>
  </template>
  
  <script>
  import { onMounted, ref } from "vue";
  
  export default {
    name: "CityMap",
    setup() {
      const map = ref(null);
      const district = ref(null);
      const polygons = ref([]);
  
      const cityName = "阜阳市"; // 替换为你的目标城市
      const loadMap = () => {
        const AMapScript = document.createElement("script");
        AMapScript.src =
          "https://webapi.amap.com/maps?v=2.0&key=93140ff854acfdbcadcc633060c0fe7f&plugin=AMap.DistrictSearch";
        AMapScript.onload = initializeMap;
        AMapScript.onerror = () => {
          console.error("高德地图脚本加载失败");
        };
        document.body.appendChild(AMapScript);
      };
  
      const initializeMap = () => {
        map.value = new AMap.Map("container", {
          center: [115.821389, 32.896672], // 替换为你的城市中心坐标
          zoom: 10, // 初始缩放级别
        });
  
        district.value = new AMap.DistrictSearch({
          subdistrict: 1, // 返回下一级行政区
          extensions: "all", // 返回行政区边界信息
          level: "city", // 查询城市级别行政区
        });
  
        district.value.search(cityName, (status, result) => {
          if (status === "complete" && result.districtList) {
            const subDistricts = result.districtList[0].districtList; // 获取下级行政区
            subDistricts.forEach((district) => {
              drawDistrict(district);
            });
          } else {
            console.error("行政区查询失败", result);
          }
        });
      };
  
      const drawDistrict = (districtData) => {
        const boundaries = districtData.boundaries;
        if (boundaries) {
          boundaries.forEach((boundary) => {
            const polygon = new AMap.Polygon({
              path: boundary, // 多边形路径
              strokeWeight: 2, // 边界线宽度
              strokeColor: "#FF33FF", // 边界线颜色
              fillColor: getRandomColor(), // 填充颜色
              fillOpacity: 0.5, // 填充透明度
            });
  
            // 添加点击事件
            polygon.on("click", () => {
              alert(`你点击了 ${districtData.name}`);
            });
  
            map.value.add(polygon);
            polygons.value.push(polygon);
          });
        }
      };
  
      const getRandomColor = () => {
        const letters = "0123456789ABCDEF";
        let color = "#";
        for (let i = 0; i < 6; i++) {
          color += letters[Math.floor(Math.random() * 16)];
        }
        return color;
      };
  
      onMounted(() => {
        loadMap();
      });
  
      return {};
    },
  };
  </script>
  
  <style>
  #container {
    width: 100%;
    height: 100vh;
    margin: 0;
  }
  </style>
  